<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">

                <el-form-item label="时间范围">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')"
                        :picker-options="pickerOptions" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between">
                <div>{{str1}}(时段)刷新率</div>
            </div>
            <div class="police-count1" ref="chart1"></div>
            <div class="flex_between">
                <div>{{ str2 }}(时段)启动App次数</div>
            </div>
            <div class="police-count6" ref="chart6"></div>
            <div class="flex_between">
                <div>{{ str }}人均启动app次数</div>
            </div>
            <div class="police-count2" ref="chart2"></div>
            <div class="flex_between">
                <div>{{ str }}人均进web次数</div>
            </div>
            <div class="police-count5" ref="chart5"></div>
            <div class="flex_between">
                <div>{{ str }}APP/Web活跃人数</div>
            </div>
            <div class="police-count3" ref="chart3"></div>
            <div class="flex_between">
                <div>{{ str }}刷新率</div>
            </div>
            <div class="police-count4" ref="chart4"></div>


        </el-card>
    </div>
</template>
<script>


import { getFaceTokens, getTokens } from "@/api/beauty";
import { daily_avg_app_entry_per_user, reportSummary, queryAppDailyActiveUsers, queryWebDailyActiveUsers,queryAggregatedStats } from "@/api/wa";
import pk from "@/utils/pk";
import * as XLSX from "xlsx";
export default {
    name: "subscription",
    data() {
        return {
            languageContent: '',
            goalLanguage: "zh_CN",
            languageList: [],
            translateLoading: false,
            pkList: [],

            queryParams: {
                dateRange: {
                    start: '',
                    end: ''
                },
            },
            queryParams1: {
                dateRange: {
                    start: '',
                    end: ''
                },
            }, 
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                comment_type: "",
            },
            search: "",
            rules: {
                comment_type: [
                    { required: true, message: "请输入类型", trigger: "blur" },
                ],
            },
            value1: "",
            chartContainer1: null,
            option1: {},
            chartData: [],
            chartContainer2: null,
            option2: {},
            chartData2: [],
            chartContainer3: null,
            option3: {},
            chartData3: [],
            chartContainer4: null,
            option4: {},
            chartData4: [],
            chartContainer5: null,
            option5: {},
            chartData5: [],
            option6: {},
            chartData6: [],
            isLoading1: true,
            chart1: null,
            chart2: null,
            chart3: null,
            chart4: null,
            chart5: null,
            chart6: null,

            loadingOption: {
                text: '',
                color: '#409eff',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            },
            pk: '',
            pickerOptions: {

            },
            invalidDateRange: false,
            str: '近30天',
            conversionRateMean: 0,
            str1: '近2天',
            str2: '24小时内',
            ws: null // WebSocket 实例
        };
    },
    created() {
         
    },

    mounted() {
         
        // this.pickerOptions = {
        //     onPick: ({ maxDate, minDate }) => {
        //         if (minDate && maxDate) {
        //             // 验证选择的日期范围
        //             const oneMonthLater = new Date(minDate);
        //             oneMonthLater.setMonth(oneMonthLater.getMonth() + 1);

        //             if (maxDate > oneMonthLater) {
        //                 // 如果超过一月范围
        //                 this.$nextTick(() => {
        //                     alert('选择的日期范围不能超过一个月');
        //                     this.value1 = []
        //                     // 立即重置 maxDate 以取消选择
        //                     this.invalidDateRange = true; // 设置标志位为 true
        //                 });
        //             } else {
        //                 this.invalidDateRange = false; // 设置标志位为 false
        //             }
        //         }
        //     }
        // };
        const { pk } = this.$route.query;
        this.queryParams.pk = pk
        this.pk = pk
        this.getStatistics2();
        this.getStatistics3();
        this.getStatistics4();
        this.getStatistics5();
     
        this.getStatistics6();
        setTimeout(() => {
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams1.dateRange.start = null;
            this.queryParams1.dateRange.end = null;
            this.getStatistics();
        })
    


    },
    methods: {

        formatDate(date) {
            const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
            return new Date(date).toLocaleDateString('zh-CN', options);
        },
        async getStatistics() {
            // 如果没有设置日期范围，则初始化日期范围：从上个月到今天
            if (!this.queryParams.dateRange || !this.queryParams.dateRange.start) {
                this.initDateRange();
            }

            const query = {
                dateRange: this.queryParams.dateRange
            };
            this.chart1 = this.$echarts.init(this.$refs.chart1);
            // 显示加载动画
            this.chart1.showLoading(this.loadingOption);
            console.log(query,'111')
            let { data } = await reportSummary(query);
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.time_range);
            const current_refresh_rate = data.map(item => item.current_refresh_rate);
            const web_count = data.map(item => item.web_count);
            const reflash_count = data.map(item => item.reflash_count);
            const mode_count = data.map(item => item.mode_count);

            this.option1 = {
                color: ['#3489FF'],
                grid: {
                    left: '4%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: current_refresh_rate, // 设置 y 轴数据
                    type: 'line', // 这里设置为折线图
                    smooth: false, // 设置平滑曲线
                    lineStyle: {
                        width: 3,
                        type: 'solid' // 也可以是 'dashed' 或 'dotted'
                    },
                    itemStyle: {
                        borderWidth: 2,
                        borderColor: '#3489FF',
                        color: '#3489FF'
                    },
                    symbol: 'circle', // 标记的图形，可以是 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
                    symbolSize: 8,
                    showSymbol: true,
                    areaStyle: {
                        opacity: 0.2 // 添加半透明填充颜色
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%' // 显示百分号
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                    时段: ${dates[index]}<br/>
                    进入web人次: ${web_count[index]}<br/>
                    刷新人次: ${reflash_count[index]}<br/>
                    切mode人次: ${mode_count[index]}
                `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };


            setTimeout(() => {
                this.initChart1();
                this.chart1.hideLoading();
            });
        },
        async getStatistics2() {

            if (!this.queryParams1.dateRange.start) {
                this.initDateRange1();

            }
            let query = {
                dateRange: this.queryParams1.dateRange,

            }
            console.log(this.queryParams1,'this.queryParams1')
            console.log(query)
            this.chart2 = this.$echarts.init(this.$refs.chart2);
            // 显示加载动画
            this.chart2.showLoading(this.loadingOption);
            let { data } = await daily_avg_app_entry_per_user(query);
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const avg_start_count = data.map(item => item.avg_start_count);
            const avg_cold_start_count = data.map(item => item.avg_cold_start_count);
            const avg_warm_start_count = data.map(item => item.avg_warm_start_count);
            const count = data.map(item => item.count);
            const start_count = data.map(item => item.start_count);
            const cold_start_count = data.map(item => item.cold_start_count);
            const warm_start_count = data.map(item => item.warm_start_count);
            this.option2 = {
                color: ['#3489FF'],
                grid: {
                    left: '2%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: avg_start_count, // 设置 y 轴数据
                    type: 'line',
                    smooth: false,
                    lineStyle: {
                        width: 3,
                        type: 'solid' // 也可以是 'dashed' 或 'dotted'
                    },
                    itemStyle: {
                        borderWidth: 2,
                        borderColor: '#3489FF',
                        color: '#3489FF'
                    },
                    symbol: 'circle', // 标记的图形，可以是 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
                    symbolSize: 8,
                    showSymbol: true,
                    areaStyle: {
                        opacity: 0.2 // 添加半透明填充颜色
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                                日期: ${dates[index]}<br/>
                                人均冷启动: ${avg_cold_start_count[index]}<br/>
                                人均热启动: ${avg_warm_start_count[index]}<br/>
                                总人数: ${count[index]}<br/>
                                总启动: ${start_count[index]}<br/>
                                总冷启动: ${cold_start_count[index]}<br/>
                                总热启动: ${warm_start_count[index]}
                            `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart2();
                this.chart2.hideLoading();

            })
        },
        initDateRange() {
            const now = new Date();
            const threeDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);
            threeDaysAgo.setHours(0, 0, 0, 0);
            const startDate = threeDaysAgo.toISOString().slice(0, 10);
            const endDate = now.toISOString().slice(0, 10);

            this.queryParams.dateRange.start = startDate;
            this.queryParams.dateRange.end = endDate;
        },
        initDateRange1() {
            const now = new Date();
            const threeDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
            threeDaysAgo.setHours(0, 0, 0, 0);
            const startDate = threeDaysAgo.toISOString().slice(0, 10);
            const endDate = now.toISOString().slice(0, 10);

            this.queryParams1.dateRange.start = startDate;
            this.queryParams1.dateRange.end = endDate;
        },
        async getStatistics3() {

             
            // 如果没有设置日期范围，则初始化日期范围：从上个月到今天
            if (!this.queryParams1.dateRange || !this.queryParams1.dateRange.start) {
                this.initDateRange1();
            }

            const query = {
                dateRange: this.queryParams1.dateRange
            };
            // 初始化图表容器（假设 this.$refs.chart3 是图表 DOM 引用）
            this.chart3 = this.$echarts.init(this.$refs.chart3);
            // 显示加载动画
            this.chart3.showLoading(this.loadingOption);

            try {
                // 并行获取两组数据
                const [appResponse, webResponse] = await Promise.all([
                    queryAppDailyActiveUsers(query),
                    queryWebDailyActiveUsers(query)
                ]);
                // 假设返回的数据结构为 { data: [...] }
                const appData = appResponse.data;
                const webData = webResponse.data;

                // 提取日期数组 —— 假定 appData 与 webData 拥有相同的日期序列
                const dates = appData.map(item => item.date);
                // 提取 App 和 Web 的日活数据
                // 这里假设数据字段为 count 或 userCount，根据实际接口调整字段名
                const appDailyUsers = appData.map(item => item.count);
                const webDailyUsers = webData.map(item => item.dau);

                // 构造 option3 对象
                this.option3 = {
                    color: ['#3489FF', '#FF5722'],  // 第一条为蓝色 (App日活)，第二条为橙色 (Web日活)
                    grid: {
                        left: '5%',
                        right: '0%'
                    },
                    xAxis: [{
                        type: 'category',
                        data: dates,
                        axisLine: { show: false },
                        axisTick: { show: false },
                        axisLabel: {
                            fontSize: 13,
                            color: '#999999',
                            margin: 13
                        },
                        splitLine: {
                            lineStyle: {
                                show: true,
                                color: '#DDDDDD'
                            }
                        }
                    }],
                    yAxis: [{
                        type: 'value',
                        axisLine: { show: false },
                        axisTick: { show: false },
                        axisLabel: {
                            fontSize: 13,
                            color: '#999999',
                            margin: 13
                        },
                        splitLine: {
                            lineStyle: {
                                show: true,
                                color: '#DDDDDD'
                            }
                        }
                    }],
                    series: [
                        {
                            name: 'App日活',
                            data: appDailyUsers,
                            type: 'line',
                            smooth: false,
                            lineStyle: {
                                width: 3,
                                type: 'solid'
                            },
                            itemStyle: {
                                borderWidth: 2,
                                borderColor: '#3489FF',
                                color: '#3489FF'
                            },
                            symbol: 'circle',
                            symbolSize: 8,
                            showSymbol: true,
                            label: {
                                show: true,
                                position: 'top'
                            }
                        },
                        {
                            name: 'Web日活',
                            data: webDailyUsers,
                            type: 'line',
                            smooth: false,
                            lineStyle: {
                                width: 3,
                                type: 'solid'
                            },
                            itemStyle: {
                                borderWidth: 2,
                                borderColor: '#FF5722',
                                color: '#FF5722'
                            },
                            symbol: 'circle',
                            symbolSize: 8,
                            showSymbol: true,
                            label: {
                                show: true,
                                position: 'top'
                            }
                        }
                    ],
                    tooltip: {
                        trigger: 'axis',
                        backgroundColor: 'rgba(32, 33, 36,.7)',
                        borderColor: 'rgba(32, 33, 36,0.20)',
                        borderWidth: 1,
                        textStyle: {
                            color: '#fff',
                            fontSize: '12'
                        },
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        },
                        formatter: function (params) {
                            // 根据返回的 params 数组，第0项为 App 日活、第1项为 Web 日活
                            const index = params[0].dataIndex;
                            return `
                        日期: ${dates[index]}<br/>
                        App日活: ${appDailyUsers[index]}<br/>
                        Web日活: ${webDailyUsers[index]}
                    `;
                        }
                    },
                    dataZoom: {
                        type: 'inside'
                    },
                    legend: {
                        data: ['App日活', 'Web日活'],
                        textStyle: {
                            color: '#999999'
                        },
                        // bottom: '0',   // 距离容器底部5%（也可以使用具体的像素值，例如 10）
                        // left: 'center'  // 居中显示
                    }
                };

                //延时执行图表初始化（也可以直接执行）
                setTimeout(() => {
                    this.initChart3();
                    this.chart3.hideLoading();
                });
            } catch (error) {
                console.error("Error fetching statistics for chart3:", error);
                this.chart3.hideLoading();
                // 错误处理中可以显示错误提示信息
            }
        },
        async getStatistics4() {
            // 如果没有设置日期范围，则初始化日期范围：从上个月到今天
            if (!this.queryParams1.dateRange || !this.queryParams1.dateRange.start) {
                this.initDateRange1();
            }

            const query = {
                dateRange: this.queryParams1.dateRange
            };
            this.chart4 = this.$echarts.init(this.$refs.chart4);
            // 显示加载动画
            this.chart4.showLoading(this.loadingOption);
            let { data } = await queryWebDailyActiveUsers(query);
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const dau = data.map(item => item.dau);
            const web_count = data.map(item => item.web_count);
            const reflash_count = data.map(item => item.reflash_count);
            const mode_count = data.map(item => item.mode_count);
            const refresh_rate = data.map(item => item.refresh_rate);


            this.option4 = {
                color: ['#3489FF'],
                grid: {
                    left: '3.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: refresh_rate, // 设置 y 轴数据
                    type: 'line', // 这里设置为折线图
                    smooth: false, // 设置平滑曲线
                    lineStyle: {
                        width: 3,
                        type: 'solid' // 也可以是 'dashed' 或 'dotted'
                    },
                    itemStyle: {
                        borderWidth: 2,
                        borderColor: '#3489FF',
                        color: '#3489FF'
                    },
                    symbol: 'circle', // 标记的图形，可以是 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
                    symbolSize: 8,
                    showSymbol: true,
                    areaStyle: {
                        opacity: 0.2 // 添加半透明填充颜色
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%' // 显示百分号
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                    日期: ${dates[index]}<br/>
                    web日活: ${dau[index]}<br/>
                    进入web人次: ${web_count[index]}<br/>
                    刷新人次: ${reflash_count[index]}<br/>
                    切mode人次: ${mode_count[index]}
                `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart4();
                this.chart4.hideLoading();
            })
        },
        async getStatistics5() {
            // 日期范围初始化逻辑与之前一致
            if (!this.queryParams1.dateRange || !this.queryParams1.dateRange.start) {
                this.initDateRange1();
            }

            const query = { dateRange: this.queryParams1.dateRange };

            // 初始化图表容器
            this.chart5 = this.$echarts.init(this.$refs.chart5);
            this.chart5.showLoading(this.loadingOption);

            try {
                // 并行获取数据
                const [appResponse, webResponse] = await Promise.all([
                    queryAppDailyActiveUsers(query),
                    queryWebDailyActiveUsers(query)
                ]);

                const appData = appResponse.data;
                const webData = webResponse.data;

                // 按日期合并数据，过滤无效数据
                const dateMap = new Map();

                // 填充App日活数据
                appData.forEach(item => {
                    dateMap.set(item.date, {
                        appCount: item.count,
                        webCount: null,
                        webDau: null
                    });
                });

                // 填充Web数据
                webData.forEach(item => {
                    const entry = dateMap.get(item.date) || {};
                    entry.webCount = item.web_count; // 总进Web次数
                    entry.webDau = item.dau;         // Web日活人数
                    dateMap.set(item.date, entry);
                });

                // 转换为数组并按日期排序
                const processedData = Array.from(dateMap.entries())
                    .map(([date, data]) => ({ date, ...data }))
                    .filter(item => item.appCount != null && item.webCount != null && item.webDau != null)
                    .sort((a, b) => new Date(a.date) - new Date(b.date));

                // 计算指标
                const dates = processedData.map(d => d.date);
                const appAvgData = processedData.map(d =>
                    d.appCount === 0 ? 0 : (d.webCount / d.appCount).toFixed(2)
                );
                const webAvgData = processedData.map(d =>
                    d.webDau === 0 ? 0 : (d.webCount / d.webDau).toFixed(2)
                );

                // 构造图表配置
                this.option5 = {
                    color: ['#FF5722', '#3489FF'], // 蓝色和粉色区分两条线
                    grid: {
                        left: '5%',
                        right: '0%'
                    },
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLine: { show: false },
                        axisTick: { show: false },
                        axisLabel: {
                            fontSize: 13,
                            color: '#999999',
                            margin: 13
                        }
                    },
                    yAxis: {
                        type: 'value',
                        axisLine: { show: false },
                        axisTick: { show: false },
                        axisLabel: {
                            fontSize: 13,
                            color: '#999999',
                            margin: 13
                        },
                        splitLine: {
                            lineStyle: { color: '#DDDDDD' }
                        },
                        // 可选：添加格式化显示为次数（如 0.5 显示为 0.5次）
                        axisLabel: {
                            formatter: value => `${value.toFixed(1)}次`
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        backgroundColor: 'rgba(32, 33, 36, .7)',
                        borderColor: 'rgba(32, 33, 36, 0.2)',
                        textStyle: { color: '#fff' },
                        formatter: params => {
                            const index = params[0].dataIndex;
                            const data = processedData[index];
                            return `
            日期: ${data.date}<br/>
            App人均: ${appAvgData[index] }次<br/>
            Web人均: ${webAvgData[index] }次
          `;
                        }
                    },
                    legend: {
                        data: ['App日活人均进Web次数', 'Web日活人均进Web次数'],
                        textStyle: { color: '#999999' },
                    },
                    series: [
                        {
                            name: 'App日活人均进Web次数',
                            type: 'line',
                            smooth: true,
                            data: appAvgData,
                            symbol: 'circle',
                            symbolSize: 8,
                            lineStyle: { width: 3 },
                            itemStyle: { color: '#3489FF' },
                            label: { show: true, position: 'top'  }
                        },
                        {
                            name: 'Web日活人均进Web次数',
                            type: 'line',
                            smooth: true,
                            data: webAvgData, 
                            symbol: 'circle',
                            symbolSize: 8,
                            lineStyle: { width: 3 },
                            itemStyle: { color: '#FF5722' },
                            label: { show: true, position: 'top' }
                        }
                    ],
                    dataZoom: { type: 'inside' }
                };

                // 渲染图表
                setTimeout(() => {
                    this.initChart5();
                    this.chart5.hideLoading();
                });
            } catch (error) {
                console.error("Error fetching statistics for chart5:", error);
                this.chart5.hideLoading();
            }
        },
        async getStatistics6() {
            // 如果没有设置日期范围，则初始化日期范围：从上个月到今天
            if (!this.queryParams.dateRange || !this.queryParams.dateRange.start) {
                this.initDateRange();
            }
            const query = {
                dateRange: this.queryParams.dateRange
            };
            

            // 初始化图表容器（假设 this.$refs.chart6 是图表 DOM 引用）
            this.chart6 = this.$echarts.init(this.$refs.chart6);
            // 显示加载动画
            this.chart6.showLoading(this.loadingOption);

            try {
                // 调用接口获取聚合数据
                const response = await queryAggregatedStats(query);
                const aggregatedData = response.data;

                // x 轴标签（小时）
                const dates = aggregatedData.map(item => item.hour_start);
                // 冷启动、热启动、活跃人数
                const coldStarts = aggregatedData.map(item => item.total_cold_starts);
                const warmStarts = aggregatedData.map(item => item.total_warm_starts);
                const userCounts = aggregatedData.map(item => item.user_count);

                // 构造图表配置
                this.option6 = {
                    color: ['#3489FF', '#FF5722', '#9C27B0'],
                    grid: {
                        left: '5%',
                        right: '0%'
                    },
                    xAxis: [{
                        type: 'category',
                        data: dates,
                        axisLine: { show: false },
                        axisTick: { show: false },
                        axisLabel: {
                            fontSize: 13,
                            color: '#999999',
                            margin: 13
                        },
                        splitLine: {
                            lineStyle: {
                                show: true,
                                color: '#DDDDDD'
                            }
                        }
                    }],
                    yAxis: [{
                        type: 'value',
                        axisLine: { show: false },
                        axisTick: { show: false },
                        axisLabel: {
                            fontSize: 13,
                            color: '#999999',
                            margin: 13
                        },
                        splitLine: {
                            lineStyle: {
                                show: true,
                                color: '#DDDDDD'
                            }
                        }
                    }],
                    series: [
                        {
                            name: '冷启动次数',
                            data: coldStarts,
                            type: 'line',
                            smooth: false,
                            lineStyle: {
                                width: 3,
                                type: 'solid'
                            },
                            itemStyle: {
                                borderWidth: 2,
                                borderColor: '#3489FF',
                                color: '#3489FF'
                            },
                            symbol: 'circle',
                            symbolSize: 8,
                            showSymbol: true,
                            label: {
                                show: true,
                                position: 'top'
                            }
                        },
                        {
                            name: '热启动次数',
                            data: warmStarts,
                            type: 'line',
                            smooth: false,
                            lineStyle: {
                                width: 3,
                                type: 'solid'
                            },
                            itemStyle: {
                                borderWidth: 2,
                                borderColor: '#FF5722',
                                color: '#FF5722'
                            },
                            symbol: 'circle',
                            symbolSize: 8,
                            showSymbol: true,
                            label: {
                                show: true,
                                position: 'top'
                            }
                        },
                        // 新增“活跃人数”系列
                        {
                            name: '活跃人数',
                            data: userCounts,
                            type: 'line',
                            smooth: false,
                            lineStyle: {
                                width: 3,
                                type: 'solid'
                            },
                            itemStyle: {
                                borderWidth: 2,
                                borderColor: '#9C27B0',
                                color: '#9C27B0'
                            },
                            symbol: 'circle',
                            symbolSize: 8,
                            showSymbol: true,
                            label: {
                                show: true,
                                position: 'top'
                            }
                        }
                    ],
                    tooltip: {
                        trigger: 'axis',
                        backgroundColor: 'rgba(32, 33, 36,0.7)',
                        borderColor: 'rgba(32, 33, 36,0.2)',
                        borderWidth: 1,
                        textStyle: {
                            color: '#fff',
                            fontSize: 12
                        },
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        },
                        formatter: (params) => {
                            // 使用 params[0] 来获取 dataIndex，这样可读性较好
                            const idx = params[0].dataIndex;
                            const data = aggregatedData[idx];
                            return `
                    日期: ${data.hour_start}<br/>
                    冷启动次数: ${data.total_cold_starts}<br/>
                    热启动次数: ${data.total_warm_starts}<br/>
                    活跃用户数: ${data.user_count}<br/>
                    人均启动次数: ${data.per_user_starts}<br/>
                    人均冷启动次数: ${data.per_user_cold_starts}<br/>
                    人均热启动次数: ${data.per_user_warm_starts}
                `;
                        }
                    },
                    dataZoom: {
                        type: 'inside'
                    },
                    legend: {
                        data: ['冷启动次数', '热启动次数', '活跃人数'],
                        textStyle: {
                            color: '#999999'
                        }
                    }
                };

                // 延时执行图表初始化
                setTimeout(() => {
                    this.initChart6();
                    this.chart6.hideLoading();
                });
            } catch (error) {
                console.error("Error fetching statistics for chart6:", error);
                this.chart6.hideLoading();
                // 可以在此处进行错误提示
            }
        },

        timeChange() {
            if (this.invalidDateRange) return; // 如果标志位为 true，则退出
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.queryParams1.dateRange.start = this.value1[0];
            this.queryParams1.dateRange.end = this.value1[1];
            this.str = this.value1[0] + '-' + this.value1[1]
            this.str1 = this.value1[0] + '-' + this.value1[1]
            this.str2 = this.value1[0] + '-' + this.value1[1]

            this.getStatistics();
            this.getStatistics2();
            this.getStatistics3();
            this.getStatistics4();
            this.getStatistics5();
            this.getStatistics6();

        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },

        resetQuery() {
            this.queryParams.state = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams1.dateRange.start = null;
            this.queryParams1.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.str = '近30天'

            this.getStatistics2();
            this.getStatistics3();
            this.getStatistics4();
            this.getStatistics5();
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.getStatistics6();
            setTimeout(() => {
                this.queryParams.dateRange.start = null;
                this.queryParams.dateRange.end = null;
                this.queryParams1.dateRange.start = null;
                this.queryParams1.dateRange.end = null;
                this.getStatistics();
            })
            


        },
        async handleExport() {
            this.loading = true;
            let { data } = await calculateDailySuccessfulPayments(this.queryParams);

            const headers = {
                date: '日期',
                count: '续订人数'
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },
        async handleExport2() {
            this.loading = true;
            let { data } = await calculateDailySuccessfulRefunds(this.queryParams);

            const headers = {
                date: '日期',
                count: '退款人数'
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },
        async handleExport3() {
            this.loading = true;
            let { data } = await calculateConversionRate(this.queryParams);

            const headers = {
                date: '日期',
                initialCount: '试用',
                renewalCount: '续费人数',
                conversionRate: '转正率',
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },
        async handleExport4() {
            this.loading = true;
            let { data } = await calculateDailyDirectPurchases(this.queryParams);

            const headers = {
                date: '日期',
                count: '直接购买人数',
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },

        initChart1() {
            this.chartContainer1 = this.$echarts.init(document.querySelector('.police-count1'))
            this.chartContainer1.setOption(this.option1)
        },
        initChart2() {
            this.chartContainer2 = this.$echarts.init(document.querySelector('.police-count2'))
            this.chartContainer2.setOption(this.option2)
        },
        initChart3() {
            this.chartContainer3 = this.$echarts.init(document.querySelector('.police-count3'))
            this.chartContainer3.setOption(this.option3)
        },
        initChart4() {
            this.chartContainer4 = this.$echarts.init(document.querySelector('.police-count4'))
            this.chartContainer4.setOption(this.option4)
        },
        initChart5() {
            this.chartContainer5 = this.$echarts.init(document.querySelector('.police-count5'))
            this.chartContainer5.setOption(this.option5)
        },
        initChart6() {
            this.chartContainer6 = this.$echarts.init(document.querySelector('.police-count6'))
            this.chartContainer6.setOption(this.option6)
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
}

.statistics-container {
    display: flex;
    flex-wrap: wrap;
    /* 自动换行 */
    gap: 10px;
    /* 数据块之间的间距 */
    padding: 10px;
    border: 1px solid #ddd;
    margin-bottom: 20px;
    font-size: 14px;
}

.item {
    background-color: #f9f9f9;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    display: inline-block;
    /* 使得每个元素成为一块 */
    white-space: nowrap;
    /* 防止单个元素中的文本换行 */
}

.police-count1,
.police-count2,
.police-count3,
.police-count4,
.police-count5,
.police-count6,
.police-count7,
.police-count8 {
    width: 100%;
    min-width: 1000px;
    height: 350px;
    color: #000;
}


.loading .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.loading-spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg) !important;
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>